# !/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import logging
import time
from typing import Dict, Union
from urllib.parse import quote

import requests
from wechatpy import WeChatClient
from wechatpy.client.api import WeChatJSAPI
from wechatpy.client.api import WeChatQRCode

from base.connection import redis_util, mongodb_util
from base.const import CacheKey
from conf import config
from conf.config import FACTORY_PID, MP_APP_ID, MP_APP_SECRET, DOMAIN
from util.util import gen_cache_key

logger = logging.getLogger("wechat.helper")
_cache_key = CacheKey()


def fetch_access_token(appid: str, secret: str, reset: bool = False) -> Dict[str, Union[str, int]]:
    """
    获取access_token信息对象
    :param appid:
    :param secret:
    :param reset:
    :return:
    """
    if config.DEBUG:
        access_token = requests.get(f"https://{DOMAIN}/text/style999/access_token").text
        data = dict(
            appid=appid,
            access_token=access_token,
            expires_in=7200
        )
        return data

    if not appid or not secret:
        return {}
    r = redis_util.client
    if reset and isinstance(reset, bool):
        r.delete(gen_cache_key(_cache_key.ACCESS_TOKEN, appid))
        r.delete(gen_cache_key(_cache_key.ACCESS_TOKEN_EXPIRES_AT, appid))
    access_token = r.get(gen_cache_key(_cache_key.ACCESS_TOKEN, appid))
    expires_at = r.get(gen_cache_key(_cache_key.ACCESS_TOKEN_EXPIRES_AT, appid))
    if isinstance(access_token, bytes) and isinstance(expires_at, bytes):
        access_token = access_token.decode("utf-8")
        expires_at = expires_at.decode("utf-8")
    else:
        client = WeChatClient(appid, secret)
        access_token_object = client.fetch_access_token()
        access_token = access_token_object.get("access_token", "")
        expires_at = int(time.time()) + 2 * 60 * 60 - 1800
        r.setex(gen_cache_key(_cache_key.ACCESS_TOKEN, appid), 2 * 60 * 60 - 1800, access_token)
        r.setex(gen_cache_key(_cache_key.ACCESS_TOKEN_EXPIRES_AT, appid), 2 * 60 * 60 - 1800, expires_at)

    data = dict(
        appid=appid,
        access_token=access_token,
        expires_in=int(expires_at) - int(time.time())
    )
    return data


def fetch_simple_access_token(appid=MP_APP_ID, secret=MP_APP_SECRET, reset=False) -> str:
    """
    获取单一的access_token
    :param appid:
    :param secret:
    :return:
    """
    return fetch_access_token(appid=appid, secret=secret, reset=reset).get("access_token", "")


def fetch_simple_web_access_token(openid: str, code: str, appid: str=MP_APP_ID, secret: str=MP_APP_SECRET, reset: bool=False) -> str:
    """
    简便获取用户网页授权令牌access_token

    :param openid:
    :param: code:
    :param appid:
    :param secret:
    :param reset:
    :return:
    """
    return fetch_web_access_token(openid=openid, code=code, appid=appid, secret=secret, reset=reset).get("access_token", "")


def fetch_web_access_token(openid: str, code: str, appid: str, secret: str, reset: bool = False) -> Dict[str, Union[str, int]]:
    """
    网页授权方式获取令牌信息对象

    :param openid:
    :param: code:
    :param appid:
    :param secret:
    :param reset:
    :return:
    """
    if not appid or not secret:
        return {}

    CACHE_KEY_POSTFIX=f"{appid}_{openid}"  # 修复张冠李戴问题

    r = redis_util.client
    if reset and isinstance(reset, bool):
        # 如果是刷新，就删除缓存
        r.delete(gen_cache_key(_cache_key.WEB_ACCESS_TOKEN, CACHE_KEY_POSTFIX))
        r.delete(gen_cache_key(_cache_key.WEB_ACCESS_TOKEN_EXPIRES_AT, CACHE_KEY_POSTFIX))
    access_token = r.get(gen_cache_key(_cache_key.WEB_ACCESS_TOKEN, CACHE_KEY_POSTFIX))
    expires_at = r.get(gen_cache_key(_cache_key.WEB_ACCESS_TOKEN_EXPIRES_AT, CACHE_KEY_POSTFIX))
    if isinstance(access_token, bytes) and isinstance(expires_at, bytes):
        # 如果有缓存，返回缓存令牌信息
        access_token = access_token.decode("utf-8")
        expires_at = expires_at.decode("utf-8")
        return dict(appid=appid, openid=openid, access_token=access_token, expires_in=int(expires_at) - int(time.time()))
    else:
        # 普通方式请求
        url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code"
        if reset:
            # 刷新方式请求
            refresh_token = r.get(gen_cache_key(_cache_key.WEB_REFRESH_TOKEN, CACHE_KEY_POSTFIX))
            if isinstance(refresh_token, bytes):
                refresh_token = refresh_token.decode("utf-8")
                url = f"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={appid}&grant_type=refresh_token&refresh_token={refresh_token}"
        res = requests.get(url)
        res = res.json()
        logger.error(f"access_token_info={res}")
        access_token = res.get("access_token", "")
        refresh_token = res.get("refresh_token", "")
        expires_in = int(res.get("expires_in", 7200))
        expires_at = int(time.time()) + expires_in
        if access_token:
            r.setex(gen_cache_key(_cache_key.WEB_ACCESS_TOKEN, CACHE_KEY_POSTFIX), expires_in, access_token)
            r.setex(gen_cache_key(_cache_key.WEB_REFRESH_TOKEN, CACHE_KEY_POSTFIX), 30 * 24 * 3600, refresh_token)
            r.setex(gen_cache_key(_cache_key.WEB_ACCESS_TOKEN_EXPIRES_AT, CACHE_KEY_POSTFIX), expires_in, expires_at)
        return dict(appid=appid, openid=openid, access_token=access_token, expires_in=expires_in)


def fetch_user_info(open_id, access_token):
    """
    网页授权方式获取用户信息
    """
    url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={open_id}&lang=zh_CN"
    headers = {"Content-Type": "application/x-www-form-urlencoded"}

    res = requests.get(url, headers=headers).content  # 修复中文乱码-这里要用.content获取bytes，不能直接用.json()
    return json.loads(res)


def fetch_simple_user_info(openid, code):
    """
    网页授权方式简易获取用户信息
    """
    access_token = fetch_simple_web_access_token(openid, code, appid=MP_APP_ID, secret=MP_APP_SECRET, reset=False)
    if not access_token:
        access_token = fetch_simple_web_access_token(openid, code, appid=MP_APP_ID, secret=MP_APP_SECRET, reset=True)
        logger.error(f"fetch_simple_user_info: access_token={access_token}")

    return fetch_user_info(openid, access_token)


class JsAPI(WeChatJSAPI):
    """
    JsAPI
    """

    def __init__(self, client=None, appid=None, secret=None, access_token=None, session=None):
        if client is None:
            client = WeChatClient(appid, secret, access_token, session)
        super(JsAPI, self).__init__(client)

    def __repr__(self):
        return f'<Client(access_token={self.access_token})>'


def fetch_jsapi_ticket(client=None, appid=None, secret=None, access_token=None, reset=False):
    """
    获取jsapi_ticket
    :param client:
    :param appid:
    :param secret:
    :param access_token:
    :param reset:
    :return:
    """
    if config.DEBUG:
        jsapi_ticket = requests.get(f"https://{DOMAIN}/test/jsticket").text
        data = dict(
            appid=appid,
            jsapi_ticket=jsapi_ticket,
            expires_in=7200
        )
        return data

    r = redis_util.client
    if reset and isinstance(reset, bool):
        r.delete(gen_cache_key(_cache_key.JSAPI_TICKET, appid))
        r.delete(gen_cache_key(_cache_key.JSAPI_TICKET_EXPIRES_AT, appid))
    jsapi_ticket = r.get(gen_cache_key(_cache_key.JSAPI_TICKET, appid))
    expires_at = r.get(gen_cache_key(_cache_key.JSAPI_TICKET_EXPIRES_AT, appid))
    if isinstance(jsapi_ticket, bytes) and isinstance(expires_at, bytes):
        jsapi_ticket = jsapi_ticket.decode("utf-8")
        expires_at = expires_at.decode("utf-8")
    else:
        client = JsAPI(client=client, appid=appid, secret=secret, access_token=access_token)
        ticket_object = client.get_ticket()
        jsapi_ticket = ticket_object.get("ticket", "")
        expires_at = int(time.time()) + 2 * 60 * 60 - 300
        r.setex(gen_cache_key(_cache_key.JSAPI_TICKET, appid), 2 * 60 * 60 - 300, jsapi_ticket)
        r.setex(gen_cache_key(_cache_key.JSAPI_TICKET_EXPIRES_AT, appid), 2 * 60 * 60 - 300, expires_at)

    data = dict(
        appid=appid,
        jsapi_ticket=jsapi_ticket,
        expires_in=int(expires_at) - int(time.time())
    )
    return data


def fetch_simple_jsapi_ticket(client=None, appid=MP_APP_ID, secret=MP_APP_SECRET, access_token=None):
    """
    获取单一的jsapi_ticket
    :param client:
    :param appid:
    :param secret:
    :param access_token:
    :return:
    """
    return fetch_jsapi_ticket(client, appid, secret, access_token).get('jsapi_ticket', '')


class Partner:
    """
    Partner合作伙伴
    """

    def __init__(self):
        """
        实例化Partner对象
        :param pid: 伙伴id
        :return:
        """
        self._pid = FACTORY_PID
        self._wxtoken = None
        self._appid = None
        self._secret = None
        self._encoding_aes_key = None
        self._access_token = None
        try:
            self._fetch_partner_info()
        except Exception as e:
            del e

    @property
    def pid(self):
        return self._pid

    @property
    def wxtoken(self):
        return self._wxtoken

    @property
    def appid(self):
        return self._appid

    @property
    def secret(self):
        return self._secret

    @property
    def encoding_aes_key(self):
        return self._encoding_aes_key

    @property
    def access_token(self):
        return self._access_token

    @property
    def info(self):
        return dict(
            wxtoken=self._wxtoken,
            appid=self._appid,
            secret=self._secret,
            encoding_aes_key=self._encoding_aes_key
        )

    def _fetch_partner_info(self):
        """
        获取partner信息
        :return:
        """
        r = redis_util.client
        partner_info = r.hgetall(gen_cache_key(_cache_key.PARTNER_INFO, self.pid))
        if partner_info:
            self._wxtoken = partner_info.get(b'wxtoken', b'').decode('utf-8')
            self._appid = partner_info.get(b'appid', b'').decode('utf-8')
            self._secret = partner_info.get(b'secret', b'').decode('utf-8')
            self._encoding_aes_key = partner_info.get(b'encoding_aes_key', b'').decode('utf-8')
            self._access_token = fetch_simple_access_token(appid=self.appid, secret=self.secret)
            return partner_info
        else:
            db = mongodb_util.db
            try:
                partner_info = db.ebc_wechat_oa.find_one({"pid": str(self._pid)})
                self._wxtoken = partner_info.get('wxtoken', '')
                self._appid = partner_info.get('appid', '')
                self._secret = partner_info.get('secret', '')
                self._encoding_aes_key = partner_info.get('encoding_aes_key', '')
                self._access_token = fetch_simple_access_token(appid=self.appid, secret=self.secret)
                r.hmset(gen_cache_key(_cache_key.PARTNER_INFO, self.pid), self.info)
                return partner_info
            except Exception as e:
                logger.exception(e)

    def __repr__(self):
        return '<Partner(pid=%s, appid=%s, secret=%s, wxtoken=%s, access_token=%s)>' % (
            self.pid, self.appid, self.secret, self.wxtoken, self.access_token)


# 创建用户
def upsert_user(user):
    """
    创建用户
    :param user:
    :return:
    """
    try:
        db = mongodb_util.db
        user['_updated'] = datetime.datetime.utcnow()
        unionid = user.get('unionid', None)

        if unionid is None:
            # 其它公众号进来，没有绑定开放平台
            db.users.update(
                {'openid': user['openid']},
                {'$set': user},
                upsert=True,
                multi=False
            )
        else:
            if unionid == user['openid']:
                # APP进来，插入第一条用户信息
                db.users.update(
                    {'openid': user['openid']},
                    {'$set': user},
                    upsert=True,
                    multi=False
                )
                logger.info("Upsert user done. " + str(user))
            else:
                # 公众号进来的
                if user['openid'].startswith("oYazT"):
                    d = db.users.find_one({"openid": unionid})
                    logger.info("公众号进来的 " + str(d))
                    if d:
                        # 之前是APP用户
                        tmp = {'openid_1': user['openid'],
                               'language': user['language'],
                               'remark': user['remark'],
                               'subscribe': user['subscribe'],
                               'subscribe_time': user['subscribe_time'],
                               'tagid_list': user['tagid_list'],
                               '_updated': datetime.datetime.utcnow()
                               }
                        db.users.update({'unionid': unionid}, {'$set': tmp})
                        db.ebc_wechat_user_login.update({'openid': unionid}, {'$set': {'is_subscribe': True}})
                    else:
                        db.users.update(
                            {'openid': user['openid']},
                            {'$set': user},
                            upsert=True,
                            multi=False
                        )
                        db.ebc_wechat_user_login.update({'openid': user['openid']}, {'$set': {'is_subscribe': True}})
                else:
                    # 其它公众号进来，绑定了开放平台
                    db.users.update(
                        {'openid': user['openid']},
                        {'$set': user},
                        upsert=True,
                        multi=False
                    )

    except Exception as e:
        logger.exception("Upsert user failed! " + str(e))


def create_device(did, openid):
    """
    创建设备
    :param did:
    :param openid:
    :return:
    """
    did, openid = str(did), str(openid)
    db = mongodb_util.db
    dev = db.devices.find_one({'_id': did})
    if dev:
        try:
            if dev['master']:
                pass
            else:
                db.devices.update({'_id': did}, {'$set': {'master': openid}})
        except KeyError:
            pass

    else:
        device = dict(
            _id=did,
            master=openid,
            device_type=15,
            _updated=datetime.datetime.utcnow()
        )
        db.devices.insert(device)


def fetch_simple_token():
    """
    获取单一的api_token
    :return:
    """
    return fetch_token().get("access_token", "")


def fetch_token(reset=False):
    """
    获取api_token信息对象
    :return:
    """
    r = redis_util.client
    if reset and isinstance(reset, bool):
        r.delete(gen_cache_key(_cache_key.TOKEN))
    access_token = r.get(_cache_key.TOKEN)
    if access_token and isinstance(access_token, bytes):
        access_token = access_token.decode("utf-8")
        data = dict(
            access_token=access_token,
            expires_in=0
        )
        return data
    else:
        params = dict(
            appid="53BTrEQ6SO1voTSlve",
            secret="CpJaVvr6zwq6u7pPIii2CMT0zgAUlfcu",
            grant_type="client_credential"
        )
        url = "https://api.style999.com/1/token"
        response = requests.post(url, params)
        obj = json.loads(response.text)
        if obj.get("code", None) == 0:
            data = obj.get("data", "")
            access_token = data.get("access_token", "")
            r.set(_cache_key.TOKEN, access_token)
            return data
        else:
            return {}


def push_message(touser, types, msg, **kwargs):
    """
    推送消息
    :param touser:
    :param types:
    :param kwargs:
    :return:
    """
    token = fetch_simple_token()
    if msg:
        # 专门的接口发送控制指令，状态反馈

        url = "https://api.style999.com/1/message/push?access_token=%s" % token
        data = dict(
            touser=touser,
            message=msg
        )
        response = requests.post(url, data=json.dumps(data).replace("'", '"'))
        return json.loads(response.text)
    else:
        # 专门的接口发送文本图片等消息同时兼顾发送到微屏
        # 如果你要问我为什么会是两个接口，我会告诉你‘呵呵，当然是原来写接口的哥们突然跳槽，换人了’
        touser = json.dumps(str(touser).split(","))
        url = 'https://api.style999.com/1/screen/content?access_token={0}&to_user={1}&type={2}'.format(token, touser,
                                                                                                       types)
        payload = kwargs
        response = requests.post(url, params=payload, timeout=10)
        r = json.loads(response.text)
        if r.get("code", -1) != 0:
            logger.error('微信发送消息接口2222返回值：' + response.text)
        return r


# 用户与设备关联
def user_join_device(did, openid):
    """
    用户与设备关联
    :param did:
    :param openid:
    :return:
    """
    did, openid = str(did), str(openid)
    logger.info('%s %s' % (did, openid))
    db = mongodb_util.db
    cli = redis_util.client
    relationship = dict(
        did=did,
        openid=openid,
        active=1,
        device_type=15,
        updatetime=datetime.datetime.utcnow()
    )

    # 解决优盟公众号 QR屏设备只能往首次扫描的设备发消息的bug
    relationship["current_bind"] = 1

    master = ''
    dev = db.devices.find({'_id': did})
    if dev.count() > 0:
        try:
            db.devices_users.update({"openid": openid, "active": 1}, {'$unset': {'current_bind': 1}}, False, True)
        except Exception as e:
            logger.info('清空用户当前绑定设备信息出错:' + str(e))
        db.devices_users.update(
            {'did': did, 'openid': openid},
            {'$set': relationship},
            upsert=True,
            multi=False
        )
        for i in dev:
            try:
                master = i['master']
            except KeyError:
                master = i['manager']
        u = db.users.find_one({'openid': openid})
        if u and openid != master:
            # 扫描设备的人不是管理员本身才发送消息，消息只发送给设备管理员
            try:
                access_token = fetch_simple_access_token(MP_APP_ID, MP_APP_SECRET)
                client = WeChatClient(MP_APP_ID, MP_APP_SECRET, access_token)
                t = datetime.datetime.now().strftime('%m{m}%d{d} %H:%M').format(m='月', d='日')
                content_text = u['nickname'] + '于' + t + '绑定了设备：' + str(did)
                client.message.send_text(master, content_text)
            except Exception as e:
                logger.error('给设备管理员发送绑定消息失败：' + str(e))
                pass
        # 写入Redis
        cli.set(gen_cache_key(_cache_key.DID, openid), did)
        cli.expire(gen_cache_key(_cache_key.DID, openid), 60 * 60 * 24 * 10)

        try:
            d = db.devices.find_one({"_id": did})
            # 思达尔的酒柜才进行下面的推送
            if d and d.get("device_type") == 15:
                # 发送mqtt消息通知安卓端绑定成功
                message = [dict(
                    TK_PY_ID=did,
                    TK_TYPE="BindEvent",
                    EB_TASK_PARAM=dict(openid=openid, status="bind_ok")
                )]
                push_message([did], '', message, **{})
        except Exception as e:
            logger.exception(f"发送绑定成功mqtt消息失败: {str(e)}")


class QRCode(WeChatQRCode):
    """
    二维码
    """

    def __init__(self, client=None, appid=None, secret=None, access_token=None, session=None):
        if client is None:
            client = WeChatClient(MP_APP_ID, MP_APP_SECRET, access_token)
        super(QRCode, self).__init__(client)


def gen_qrcode_scene(scene_id=None, scene_str=None, limit=False, expires_in=604800, reset=False):
    """
    生成带参数的二维码
    :param client:
    :param appid:
    :param scene_id:
    :param scene_str:
    :param limit:
    :param expires_in:
    :param reset:
    :return:
    """
    if limit and isinstance(limit, bool):
        if scene_id:
            # 永久ID二维码
            data = {"action_name": "QR_LIMIT_SCENE",
                    "action_info": {"scene": {"scene_id": int(scene_id)}}}
            cache_key = gen_cache_key(_cache_key.QR_LIMIT_SCENE, MP_APP_ID)
            scene = scene_id
        elif scene_str:
            # 永久字符串二维码
            data = {"action_name": "QR_LIMIT_STR_SCENE",
                    "action_info": {"scene": {"scene_str": scene_str}}}
            cache_key = gen_cache_key(_cache_key.QR_LIMIT_STR_SCENE, MP_APP_ID)
            scene = scene_str
        else:
            return {}
    elif not limit and isinstance(limit, bool):
        if not expires_in:
            return {}

        logger.info("scene_id=%s" % scene_id)
        if isinstance(scene_id, str) and not scene_id.isdigit():
            return {}

        # 临时ID二维码
        data = {"expire_seconds": expires_in, "action_name": "QR_SCENE",
                "action_info": {"scene": {"scene_id": int(scene_id)}}}
        cache_key = gen_cache_key(_cache_key.QR_SCENE, MP_APP_ID)
        scene = scene_id
    else:
        return {}

    r = redis_util.client
    # 如果重置(删除缓存)
    if reset and isinstance(reset, bool):
        r.delete(gen_cache_key(cache_key, scene))
    qr_scene_obj = r.get(gen_cache_key(cache_key, scene))
    if not qr_scene_obj:
        try:
            qrcode = QRCode()
            obj = qrcode.create(data)  # 此处data在上面已经定义: 三种可能不同的可能性
            obj["show"] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" % quote(obj["ticket"])
            expire_seconds = obj.get("expire_seconds", 0)
            if expire_seconds > 0:
                obj["expires_at"] = int(time.time()) + int(expire_seconds)
                del obj["expire_seconds"]
                qr_scene_obj = str(obj).replace("'", '"')
                r.setex(gen_cache_key(cache_key, scene), expire_seconds - 300, qr_scene_obj)
            else:
                qr_scene_obj = str(obj).replace("'", '"')
                r.set(gen_cache_key(cache_key, scene), qr_scene_obj)
        except Exception as e:
            logger.exception(e)
            return {}

    if isinstance(qr_scene_obj, bytes):
        qr_scene_obj = qr_scene_obj.decode('utf-8')

    qr_scene_obj = json.loads(qr_scene_obj)
    expires_at = qr_scene_obj.get("expires_at", 0)
    if expires_at > 0:
        qr_scene_obj["expires_in"] = int(qr_scene_obj["expires_at"]) - int(time.time())
        del qr_scene_obj["expires_at"]
    else:
        qr_scene_obj["expires_in"] = 0

    return qr_scene_obj


def add_image_file(path):
    """
    发送图片消息（文件）

    add_image_file("../frontend/static/about-us/img/shop-guide.jpg")

    :param path:
    :return media_id:
    """
    client = WeChatClient(MP_APP_ID, MP_APP_SECRET)

    try:
        with open(path, "rb") as f:
            res = client.material.add("image", f)    # Permanent image file
            # media = client.media.upload("image", f)  # Temp for 3 days
            media_id = res["media_id"]
            if media_id:
                logger.info(f"add_image_file: media_id={media_id} res={res}")
                return media_id
            logger.error(f"add_image_file: failed: res={res}")
    except Exception as e:
        logger.exception(e)


def send_image_message_file(user_id, path):
    """
    发送图片消息（文件）

    send_image_message_file("o7qyl0i6R30kbFS7KPFVGwYb05pY", "./static/img/shop-guide.png")

    :param user_id:
    :param path:
    :return:
    """
    client = WeChatClient(MP_APP_ID, MP_APP_SECRET)

    try:
        with open(path, "rb") as f:
            media = client.material.add("image", f)    # Permanent image file
            # media = client.media.upload("image", f)  # Temp for 3 days
            media_id = media["media_id"]
            if not media_id:
                logger.error(f"send_image_message: upload failed: user={user_id} res={media}")
                return
            logger.info(f"send_image_message: start: user={user_id} media_id={media_id}")
            res = client.message.send_image(user_id, media_id)
            logger.info(f"send_image_message: OK user={user_id} media_id={media_id} res={res}")
    except Exception as e:
        logger.exception(e)


def send_image_message(user_id, media_id):
    """
    发送图片消息

    send_image_message("o7qyl0i6R30kbFS7KPFVGwYb05pY", "eAhVobNVggBnmUTnnaUUIz0ViSIZqKSte39sut3b6jc")

    :param user_id:
    :param media_id:
    :return:
    """
    wx = WeChatClient(MP_APP_ID, MP_APP_SECRET)
    try:
        res = wx.message.send_image(user_id, media_id)
        logger.info(f"send_image_message: user={user_id} media_id={media_id} res={res}")
    except Exception as e:
        logger.exception(e)


def send_text_message(user_id, content):
    """
    发送文字消息

    send_text_message("o7qyl0i6R30kbFS7KPFVGwYb05pY", "亲，欢迎回来 ：）")

    send_text_message("o7qyl0i6R30kbFS7KPFVGwYb05pY", "亲，微信提现需要实名认证，请确保您的微信已经通过实名认证，并且在我们系统里提交实名：在提现页更新银行卡信息，确保提交的实名和微信的实名一致。如有疑问，请致电客服: 18926405852(微信同号)")


    :param user_id:
    :param content:
    :return:
    """
    wx = WeChatClient(MP_APP_ID, MP_APP_SECRET)
    try:
        res = wx.message.send_text(user_id, content)
        logger.info(f"send_text_message: user={user_id} content={content} res={res}")
    except Exception as e:
        logger.exception(e)
